#include "sipc.h"
#include "ka.h"

static s_mode m_mode;
static const char *m_guest;

void s_set_mode(s_mode mode, const char *guest)
{
    m_mode = mode;
    m_guest = guest;
}

uint8_t buffer[RSA_SIZE / 8];
ssize_t s_read(int __fd, void *__buf, size_t __nbytes)
{

    ssize_t buffer_len = read(__fd, buffer, sizeof(buffer));
    int rc = 0;
    int __buf_len = __nbytes;
    switch (m_mode)
    {
    case S_MODE_HOST:
        rc = ka_host_decrypt(buffer, buffer_len, __buf, &__buf_len);
        break;
    case S_MODE_GUEST:
        rc = ka_guest_decrypt(m_guest, buffer, buffer_len, __buf, &__buf_len);
        break;
    default:
        return 0;
    }
    if (rc)
        return 0;
    return (ssize_t)__buf_len;
}
ssize_t s_write(int __fd, void *__buf, size_t __n)
{
    int rc = 0;
    int buffer_len = sizeof(buffer);
    int __buf_len = __n;
    switch (m_mode)
    {
    case S_MODE_HOST:
        rc = ka_host_encrypt(__buf, __buf_len, buffer, &buffer_len);
        break;
    case S_MODE_GUEST:
        rc = ka_guest_encrypt(m_guest, __buf, __buf_len, buffer, &buffer_len);
        break;
    default:
        return 0;
    }
    if (rc)
        return 0;
    return write(__fd, buffer, (size_t)buffer_len);
}